package com.hotchpotch.broadcast;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Environment;

import com.hotchpotch.util.Logg;

import java.io.File;

public class PackageDeleteBroad extends BroadcastReceiver {
    private static final String TAG = "安装包检测广播";
    private String apkName = "鸿邦商盟.apk";//apk的文件名

    @Override
    public void onReceive(Context context, Intent intent) {
        Logg.e(TAG, intent.getAction() + "");
        if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())) {//安装包安装成功
            Logg.d(TAG, "监听到系统广播,包被添加: ");
            //删除apk文件
            deleteApkfile(apkName);
        }

        if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
            Logg.d(TAG, "监听到系统广播,包被移除: ");
            Logg.d(TAG, "onReceive: " + intent.getDataString());
        }

        if (Intent.ACTION_PACKAGE_REPLACED.equals(intent.getAction())) {
            Logg.d(TAG, "监听到系统广播,包被替换: ");
            Logg.d(TAG, "onReceive: " + intent.getPackage());
            deleteApkfile(apkName);
        }
        if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
            Logg.d(TAG, "监听到系统广播,用户开机");
        }
        if (Intent.ACTION_USER_PRESENT.equals(intent.getAction())) {
            Logg.d(TAG, "监听到系统广播，用户解锁屏幕");
        }
    }

    public Boolean deleteApkfile(String apkFileName) {
        //Apk文件路径可自定义，此处用 download 文件夹
        File apkfile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath(), apkFileName);
        if (!apkfile.exists()) {
            Logg.d(TAG, "apkfile delete already! ");
        } else {
            //调用现成的文件操作方法删除文件
            if (apkfile.delete())
                Logg.d(TAG, "apkfile delete successfully! ");
        }
        return false;
    }
}
